﻿using HelperFromTheSkeleton.Model.DomainModels;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;

namespace HelperFromTheSkeleton.EFBaseRepository
{
    /// <summary>
    /// 树结构基础实现
    /// </summary>
    public class EFBaseTreeRepositoryImpl<T> : EFBaseRepositoryImpl<T> where T : TreeBaseDomain
    {
        public EFBaseTreeRepositoryImpl(DbContext hospitalWeChatPayDBEntities) : base(hospitalWeChatPayDBEntities)
        {

        }

        /// <summary>
        /// 获取树的所有下级
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<List<T>> GetAllSubsetAsync(Guid id)
        {
            var entityType = typeof(T);
            var entityName = entityType.Name;
            var sql = $@"with temp as (
                        select * from {entityName} where ID= @id 
                        union all
                        select c.* from {entityName} as c ,temp t where c.ParentID = t.ID
                        )select * from temp;";

            return await _dbSet.FromSqlRaw(sql, new[] { new SqlParameter("id", id) }).ToListAsync();
        }
    }
}
